package info.niwota.fwrite;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class SizePickDialog extends Dialog implements OnClickListener {

	public interface OnSizeChangedListener {
		void sizeChanged(int size);
	}

	private OnSizeChangedListener mListener;
	private int mSize;
	private int mColor = Color.WHITE;
	private int mBackgroundColor = Color.BLACK;

	private final static int[] view_ids = new int[] { R.id.size0, R.id.size1,
			R.id.size2, R.id.size3, R.id.size4, R.id.size5, R.id.size6,
			R.id.size7, R.id.size8, R.id.size9, R.id.size10, R.id.size11,
			R.id.size12, R.id.size13, R.id.size14, R.id.size15, R.id.size16,
			R.id.size17, R.id.size18, R.id.size19, };
	
	private static final int MAX_SIZE = 56;
	private static final String TAG = "SizePickDialog";

	private TextView[] views = new TextView[view_ids.length];
	
	public SizePickDialog(Context context, OnSizeChangedListener listener,
			int initialSize) {
		super(context);
		mListener = listener;
		mSize = initialSize;
	}



	public void setInitialSize(int mInitialSize) {
		this.mSize = mInitialSize;
	}

	public void setColor(int mColor) {
		this.mColor = mColor;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.sizedia);
		
		//
		for (int i = 0; i < view_ids.length; i++) {
			TextView tv = (TextView) findViewById(view_ids[i]);
			views[i] = tv;
			tv.setOnClickListener(this);
			if (tv.getText().equals(mSize+"")) {
				tv.setBackgroundColor(mColor);
			}
		}
	}

	@Override
	protected void onStart() {
		if (Debug.DEBUG) {
			Log.d(TAG, "onStart size: " + mSize +" color: " + mColor );
		}
		super.onStart();
		updateSelection();
	}

	@Override
	protected void onStop() {
		if (Debug.DEBUG) {
			Log.d(TAG, "onStop size: " + mSize +" color: " + mColor );
		}
		super.onStop();
	}

	private void updateSelection() {
		int s = mSize;
		if (s > 0 && s <= MAX_SIZE) {
			String st = s+"";
			for (int i = 0; i < views.length; i++) {
				if (views[i].getText().equals(st)) {
					views[i].setBackgroundColor(mColor);
				} else {
					views[i].setBackgroundColor(mBackgroundColor);
				}
			}
		}
	}
	
	public void onClick(View v) {
		if (v instanceof TextView) {
			TextView tv = (TextView) v;
			CharSequence cs = tv.getText();
			try {
				int s = Integer.parseInt(cs.toString());
				if (s > 0 && s <= MAX_SIZE && mListener != null) {
					mSize = s;
					mListener.sizeChanged(s);
					dismiss();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
